package gq.example.controller;

import gq.example.dto.FeedbackDto;
import gq.example.dto.FeedbackPageQueryDto;
import gq.example.result.PageResult;
import gq.example.result.Result;
import gq.example.service.FeedbackService;
import gq.example.vo.CommunicationVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/feedback")
@Tag(name = "回复管理")
@Slf4j
public class FeedbackController {
    @Resource
    private FeedbackService feedbackService;

    /**
     * 回复意见 (包括追加回复)
     * @param feedbackDto
     * @return
     */
    @Transactional
    @PostMapping("/add")
    @Operation(summary = "回复意见",description = "追加回复同样适用")
    public Result addFeedback(@RequestBody FeedbackDto feedbackDto) {
        log.info("用户{} 回复意见", feedbackDto.getCreateUser());

        //判断问题是否归档
        if(feedbackService.isArchived(feedbackDto.getQuestionId())){
            return Result.error("该问题已归档，无法回复");
        }

        feedbackService.addFeedback(feedbackDto);

        return Result.success("添加成功");
    }

    /**
     * 回复查看(详细)
     * @param questionId #问题id
     * @param createUser #用户id
     * @return
     */
    @Transactional
    @GetMapping("/list/{questionId}")
    @Operation(summary = "回复查看")
    public Result<List<CommunicationVo>> viewReply(@PathVariable Integer questionId, @RequestParam Long createUser) {
        log.info("用户{} 查看详情回复", createUser);

        return Result.success(feedbackService.viewReply(questionId, createUser));
    }

    /**
     * 回复查看(大体)
     * @param feedbackPageQueryDto
     * @return
     */
    @GetMapping("/page")
    @Operation(summary = "回复查看",description = "大体展示有哪些意见")
    public Result<PageResult> page(FeedbackPageQueryDto feedbackPageQueryDto) {
        log.info("用户{} 查看回复", feedbackPageQueryDto.getCreateUser());

        PageResult pageResult = feedbackService.pageQuery(feedbackPageQueryDto);
        return Result.success(pageResult);
    }

    /**
     * 意见回复数目(小红点提示)
     * @param createUser // 当前使用系统的用户id
     * @return
     */
    @GetMapping("/count")
    @Operation(summary = "查询用户未读回复数目",description = "在意见回复右上角类似小红点展示")
    public Result count(
            @Schema(description = "当前使用系统的用户id") @RequestParam Long createUser,
            @Schema(description = "部门id（回复人查看追加问消息才需要）") @RequestParam(required = false) Integer sectorId) {
        log.info("统计用户未读回复数目");
        Integer replies = 0;
        replies += feedbackService.countReplies(createUser); // 查提出问题的回复数

        //如果角色可以回复意见
        if(sectorId != null){
            replies += feedbackService.countProbe(createUser,sectorId); // 查提出者追问数
        }
        return Result.success(replies);
    }
}
